package com.flying.client.network;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelDownstreamHandler;

import com.flying.client.network.msg.OWMsg;
import com.flying.client.utils.Logger;


public class MsgEncoder extends SimpleChannelDownstreamHandler{
	
	private static final Logger logger = Logger.getLogger(MsgEncoder.class.getName());
	
	@Override
    public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        
		logger.debug("writeRequested");
		
		OWMsg msg = (OWMsg)e.getMessage();
        
        int bodyLen = 0;
        if (msg.getBodyBuffer() != null)
        {
        	bodyLen = msg.getBodyBuffer().readableBytes();
        }
        
        ChannelBuffer buffer = ChannelBuffers.buffer(OWMsg.MSG_HEADER_LEN + bodyLen);
        
        buffer.writeShort(msg.getMsgType()); //消息类型
        buffer.writeShort(msg.getMsgSeq()); //消息编号
        
        if (msg.getBodyBuffer() == null)
		{
			buffer.writeInt(0); 
		}
		else
		{
			buffer.writeInt(buffer.readableBytes());//消息长度
			
			buffer.writeBytes(msg.getBodyBuffer());
		}
        
		Channels.write(ctx,e.getFuture(),buffer);
    }
}
